interface ErnieResponse {
  id: string;
  object: string;
  created: number;
  result: string;
  is_truncated: boolean;
  need_clear_history: boolean;
  usage: {
    prompt_tokens: number;
    completion_tokens: number;
    total_tokens: number;
  }
}

export async function getAccessToken(): Promise<string> {
  const API_KEY = process.env.ERNIE_API_KEY;
  const SECRET_KEY = process.env.ERNIE_SECRET_KEY;

  const response = await fetch(
    `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${API_KEY}&client_secret=${SECRET_KEY}`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
    }
  );

  const data = await response.json();
  return data.access_token;
}

export async function callErnieBot(prompt: string): Promise<string> {
  try {
    const accessToken = await getAccessToken();
    
    const response = await fetch(
      `https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-128k-preview?access_token=${accessToken}`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          messages: [
            {
              role: 'user',
              content: prompt,
            },
          ],
          system: "你是一个专业的营养师，擅长根据用户的身体状况和目标提供个性化的饮食建议。请始终以 JSON 格式返回建议。",
          temperature: 0.7,
          top_p: 0.8,
        }),
      }
    );

    if (!response.ok) {
      throw new Error(`API 请求失败: ${response.status}`);
    }

    const data = await response.json();
    console.log('文心一言API原始响应:', data);

    if (!data.result) {
      throw new Error('API 返回数据格式错误');
    }

    return data.result;
  } catch (error) {
    console.error('调用文心一言API失败:', error);
    throw error;
  }
} 